public class RequestContext {

    // 当前线程的请求 ID
    private static final ThreadLocal<String> requestIdHolder = new ThreadLocal<>();

    // 当前线程的开始时间
    private static final ThreadLocal<Long> startTimeHolder = new ThreadLocal<>();

    // 设置当前线程的请求信息
    public static void setRequestInfo(String requestId) {
        requestIdHolder.set(requestId);
        startTimeHolder.set(System.currentTimeMillis());
    }

    // 获取请求 ID
    public static String getRequestId() {
        return requestIdHolder.get();
    }

    // 计算已耗时间
    public static long getElapsedTime() {
        Long start = startTimeHolder.get();
        return start != null ? System.currentTimeMillis() - start : 0;
    }

    // 请求结束时清理
    public static void clear() {
        requestIdHolder.remove();
        startTimeHolder.remove();
    }
}